<template>
  <div>
    <a-card :bordered="false" :bodyStyle="tstyle">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="6" :sm="24">
              <a-form-item label="开课学年">
                <a-select
                  show-search
                  allowClear
                  placeholder="请选择开课学年"
                  v-model="queryParam.schoolYearId"
                  @change="changeSchoolYear">
                  <a-select-option v-for="item of this.schoolYearList" :key="item.id">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="开课学期">
                <a-select show-search allowClear placeholder="请选择开课学期" v-model="queryParam.termId">
                  <a-select-option v-for="item of this.schoolTermList" :key="item.id">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="开课课程">
                <a-select
                  show-search
                  allowClear
                  placeholder="请选择开课课程"
                  v-model="queryParam.courseId"
                  @change="changeCourse"
                >
                  <a-select-option v-for="item of this.courseList" :key="item.id">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="6" :sm="24">
                <a-form-item label="实验项目">
                  <a-select show-search allowClear placeholder="请选择实验项目" v-model="queryParam.projectId">
                    <a-select-option v-for="item of this.projectList" :key="item.id">
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="轮次">
                  <a-select
                    show-search
                    allowClear
                    placeholder="请选择轮次"
                    v-model="queryParam.frequencyIndex"
                    :disabled="!queryParam.courseId">
                    <a-select-option v-for="item of frequencyList" :key="item">
                      {{ item }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="作业标签">
                  <a-select show-search allowClear placeholder="请选择作业标签" v-model="queryParam.homeworkTagId">
                    <a-select-option v-for="item of this.homeworkTagList" :key="item.id">
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="老师">
                  <a-select
                    show-search
                    allowClear
                    placeholder="请选择老师"
                    :disabled="!hasRole('sa') && !hasRole('ca')"
                    v-model="queryParam.teacherId">
                    <a-select-option v-for="item of this.teacherList" :key="item.id">
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </template>
            <a-col :md="6" :sm="24">
              <span class="table-page-search-submitButtons">
                <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
                <a-button style="margin-left: 8px" @click="resetQueryParam">重置</a-button>
                <a @click="toggleAdvanced" style="margin-left: 8px">
                  {{ advanced ? '收起' : '展开' }}
                  <a-icon :type="advanced ? 'up' : 'down'"/>
                </a>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>
    <a-card :bordered="false">
      <s-table
        ref="table"
        :columns="columns"
        :data="loadData"
        :alert="options.alert"
        :rowSelection="options.rowSelection"
        :rowKey="(record) => record.courseSelectionId">
        <template class="table-operator" slot="operator">
          <a-button
            type="primary"
            icon="download"
            :disabled="selectedRows.length === 0"
            @click="batchDownloadStudentHomework">下载学生作业
          </a-button>
          <a-upload
            :customRequest="batchUploadCorrectedHomeworkFile"
            :multiple="false"
            :showUploadList="false"
            name="file">
            <a-button type="primary" icon="upload">上传批改作业</a-button>
          </a-upload>

          <a-button
            type="primary"
            icon="download"
            :disabled="selectedRows.length === 0"
            @click="batchDownloadCorrectedHomework">下载批改作业
          </a-button>
          <x-down ref="batchExport" @batchExport="batchExport"/>
        </template>
        <span slot="homeworkAttachmentName" slot-scope="text, record">
          <a-popconfirm
            title="确认清空作业？"
            ok-text="确认"
            cancel-text="取消"
            @confirm="deleteStuHomework(record.homeworkId)"
          >
            <a-button size="small" type="warning" v-if="record.stuConfirmed === 1">清空作业</a-button>
          </a-popconfirm>
          <a @click="sysFileInfoDownload(record.homeworkFileId)">{{ record.homeworkAttachmentName }}</a>
        </span>
        <span slot="frequencyIndex" slot-scope="text, record">
          {{ `第${record.frequencyIndex}轮` }}
        </span>
        <span slot="homeworkCorrectedAttachmentName" slot-scope="text, record">
          <span v-if="record.homeworkCorrectedAttachmentName">
            <a @click="sysFileInfoDownload(record.correctedHomeworkFileId)">{{
              record.homeworkCorrectedAttachmentName
            }}</a>
          </span>
          <template v-else>
            <a-upload
              v-if="record.homeworkAttachmentName"
              :customRequest="uploadCorrectedHomeworkFile"
              :data="record"
              :multiple="true"
              :showUploadList="false"
              name="file">
              <a-button size="small"><a-icon type="upload" />上传</a-button>
            </a-upload>
            <span v-else>-</span>
          </template>
        </span>
        <span slot="homeworkTagNames" slot-scope="text, record" style="cursor: pointer">
          <template v-if="record.homeworkTagNames">
            <a-tag
              style="cursor: pointer"
              v-for="tag in record.homeworkTagNames.split(',')"
              :key="tag"
              @click="$refs.homeworkTag.open(record)">{{ tag }}</a-tag>
          </template>
          <template v-else>
            <a-button type="link" v-if="record.homeworkId" @click="$refs.homeworkTag.open(record)">标记</a-button>
            <span>-</span>
          </template>
        </span>
        <span slot="projectScore" slot-scope="text, record">
          <span @click="$refs.score.open(record, 0)" style="cursor: pointer">
            <a-button type="link" v-if="record.projectScore != null && record.projectScore !== undefined">
              {{ record.projectScore }}
            </a-button>
            <a-button type="link" v-else>打分</a-button>
          </span>
        </span>
        <span slot="defendScore" slot-scope="text, record">
          <span @click="$refs.score.open(record, 1)" style="cursor: pointer">
            <a-button type="link" v-if="record.defendScore !== null && record.defendScore !== undefined">{{ record.defendScore }}</a-button>
            <a-button type="link" v-else>打分</a-button>
          </span>
        </span>
      </s-table>
    </a-card>
    <score ref="score" @ok="handleOk"/>
    <homework-tag ref="homeworkTag" @ok="handleOk"/>
  </div>
</template>
<script>
  import { STable, XDown } from '@/components'
  import { mapGetters } from 'vuex'
  import { hasRole } from '@/utils/permissions'
  import {
    homeworkPageForTeacher,
    homeworkExportForTeacher,
    uploadCorrectedHomeworkFile,
    batchUploadCorrectedHomeworkFile,
    batchDownloadStudentHomework,
    batchDownloadCorrectedHomework,
    listFrequencyForTeacher,
    homeworkDelete
  } from '@/api/modular/main/courseHomeworkManage'
  import { sysFileInfoDownload } from '@/api/modular/system/fileManage'
  import { sysSchoolYearList } from '@/api/modular/system/sysSchoolYearManage'
  import { sysSchoolTermList } from '@/api/modular/system/sysSchoolTermManage'
  import { projectList } from '@/api/modular/system/projectManage'
  import { courseList } from '@/api/modular/system/courseManage'
  import { homeworkTagList } from '@/api/modular/system/homeworkTagManage'
  import { getUserByType } from '@/api/modular/system/userManage'
  import score from './score.vue'
  import homeworkTag from './homeworkTag.vue'

  export default {
    name: 'HomeworkForTeacher',
    components: {
      STable,
      XDown,
      score,
      homeworkTag
    },
    data() {
      return {
        // 高级搜索 展开/关闭
        advanced: false,
        // 查询参数
        queryParam: {
          schoolYearId: undefined,
          termId: undefined,
          courseId: undefined,
          projectId: undefined,
          frequencyIndex: undefined,
          homeworkTagId: undefined,
          teacherId: undefined,
          courseScheduleFrequencyId: undefined
        },
        frequencyList: [],
        courseList: [],
        homeworkTagList: [],
        schoolYearList: [],
        schoolTermList: [],
        projectList: [],
        teacherList: [],
        // 表头
        columns: [
          {
            title: '开课课程',
            align: 'center',
            ellipsis: true,
            dataIndex: 'courseName'
          },
          {
            title: '实验项目',
            align: 'center',
            ellipsis: true,
            dataIndex: 'projectName'
          },
          {
            title: '轮次',
            align: 'center',
            ellipsis: true,
            dataIndex: 'frequencyIndex',
            scopedSlots: { customRender: 'frequencyIndex' }
          },
          {
            title: '学生',
            align: 'center',
            ellipsis: true,
            dataIndex: 'studentName'
          },
          {
            title: '上传作业时间',
            align: 'center',
            width: '150px',
            ellipsis: true,
            dataIndex: 'homeworkUploadDate'
          },
          {
            title: '作业',
            align: 'center',
            ellipsis: true,
            width: '200px',
            dataIndex: 'homeworkAttachmentName',
            scopedSlots: { customRender: 'homeworkAttachmentName' }
          },
          {
            title: '批改作业时间',
            align: 'center',
            ellipsis: true,
            dataIndex: 'homeworkCorrectedDate'
          },
          {
            title: '批改作业',
            align: 'center',
            ellipsis: true,
            dataIndex: 'homeworkCorrectedAttachmentName',
            scopedSlots: { customRender: 'homeworkCorrectedAttachmentName' }
          },
          {
            title: '项目分数',
            align: 'center',
            dataIndex: 'projectScore',
            scopedSlots: { customRender: 'projectScore' }
          },
          {
            title: '作业标签',
            align: 'center',
            ellipsis: true,
            dataIndex: 'homeworkTagNames',
            scopedSlots: { customRender: 'homeworkTagNames' }
          },
          {
            title: '答辩分数',
            align: 'center',
            dataIndex: 'defendScore',
            scopedSlots: { customRender: 'defendScore' }
          }
        ],
        tstyle: { 'padding-bottom': '0px', 'margin-bottom': '10px' },
        // 加载数据方法 必须为 Promise 对象
        loadData: (parameter) => {
          return homeworkPageForTeacher(Object.assign(parameter, this.queryParam)).then((res) => {
            return res.data
          })
        },
        selectedRowKeys: [],
        selectedRows: [],
        options: {
          alert: {
            show: true,
            clear: () => {
              this.selectedRowKeys = []
            }
          },
          rowSelection: {
            selectedRowKeys: this.selectedRowKeys,
            onChange: this.onSelectChange
          }
        },
        allowedFileTypes: [
          'application/msword',
          'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
          'application/vnd.ms-powerpoint',
          'application/vnd.openxmlformats-officedocument.presentationml.presentation',
          'application/pdf'
        ]
      }
    },
    computed: {
      ...mapGetters(['userInfo'])
    },
    created() {
      this.init()
    },
    watch: {
      $route: {
        handler(val) {
          if (val.name === 'HomeworkForTeacher') {
            this.init()
            const params = this.$route.params
            this.queryParam = {
              ...this.queryParam,
              schoolYearId: params.schoolYearId,
              termId: params.termId,
              courseId: params.courseId,
              projectId: params.projectId,
              frequencyIndex: params.frequencyIndex,
              teacherId: params.teacherId,
              courseScheduleFrequencyId: params.courseScheduleFrequencyId
            }
            if (this.$refs.table) {
              this.$refs.table.refresh(true)
            }
          }
        },
        immediate: true
      }
    },
    methods: {
      resetQueryParam() {
        if (hasRole('sa') || hasRole('ca')) { // 如果是超级管理员或者院系管理员
          this.queryParam = {
            schoolYearId: undefined,
            termId: undefined,
            courseId: undefined,
            projectId: undefined,
            frequencyIndex: undefined,
            homeworkTagId: undefined,
            teacherId: undefined
          }
        } else {
          this.queryParam = { // 不清空老师
            ...this.queryParam,
            schoolYearId: undefined,
            termId: undefined,
            courseId: undefined,
            projectId: undefined,
            frequencyIndex: undefined,
            homeworkTagId: undefined
          }
        }
      },
      init() {
        this.getSchoolYearList()
        this.getSchoolTermList()
        this.getCourseList()
        this.getProjectList(null)
        this.getHomeworkTagList()
        this.loadTeacherList()
      },
      loadCourseScheduleFrequencyList(courseId) {
        listFrequencyForTeacher({
          courseId: courseId
        }).then((res) => {
          if (res.success) {
            this.frequencyList = res.data
          }
        })
      },
      loadTeacherList() {
        getUserByType({
          userType: 'tch',
          id: hasRole('sa') || hasRole('ca') ? null : this.userInfo.id
        }).then((res) => {
          if (res.success) {
            this.teacherList = res.data
            if (res.data.length === 1) this.queryParam.teacherId = res.data[0].id
          }
        })
      },
      /**
       * load作业标签
       */
      getHomeworkTagList() {
        homeworkTagList().then((res) => {
          if (res.success) {
            this.homeworkTagList = res.data
          }
        })
      },
      /**
       * load实验项目
       */
      getProjectList(collId) {
        projectList({
          collId: collId
        }).then((res) => {
          if (res.success) {
            this.projectList = res.data
          }
        })
      },
      /**
       * load学年列表
       */
      getSchoolYearList() {
        sysSchoolYearList().then((res) => {
          if (res.success) {
            this.schoolYearList = res.data
          }
        })
      },
      /**
       * load开课学期
       */
      getSchoolTermList(schoolYearId) {
        sysSchoolTermList({
          schoolYearId: schoolYearId
        }).then((res) => {
          if (res.success) {
            this.schoolTermList = res.data
          }
        })
      },
      /**
       * load课程
       */
      getCourseList() {
        courseList({
          collId: this.queryParam.collegeId
        }).then((res) => {
          if (res.success) {
            this.courseList = res.data
          }
        })
      },
      toggleAdvanced() {
        this.advanced = !this.advanced
      },
      /**
       * 批量导出
       */
      batchExport() {
        homeworkExportForTeacher(this.queryParam).then((res) => {
          this.$refs.batchExport.downloadfile(res)
        })
      },
      handleOk() {
        this.$refs.table.refresh()
      },
      onSelectChange(selectedRowKeys, selectedRows) {
        this.selectedRowKeys = selectedRowKeys
        this.selectedRows = selectedRows
      },
      uploadCorrectedHomeworkFile(data) {
        const file = data.file
        const fileSize = file.size
        const fileType = file.type
        if (this.allowedFileTypes.indexOf(fileType) === -1) {
          this.$message.error('请上传word,ppt,pdf文件')
          return
        }
        if (fileSize / 1024 / 1024 > 50) {
          this.$message.error('上传文件大小不能超过50M')
          return
        }
        // console.log('fileSize=', fileSize, '&fileType=', fileType)
        const formData = new FormData()
        formData.append('file', file)
        formData.append('id', data.data.homeworkId)
        uploadCorrectedHomeworkFile(formData).then((res) => {
          if (res.success) {
            this.$message.success('上传成功')
            this.$refs.table.refresh()
          } else {
            this.$message.error('上传失败：' + res.message)
          }
        })
      },
      batchUploadCorrectedHomeworkFile(data) {
        const file = data.file
        const fileSize = file.size
        const fileType = file.type
        console.log(fileType)
        if (fileType !== 'application/zip' && (file.name.substr(file.name.lastIndexOf('.')) !== '.rar' && file.name.substr(file.name.lastIndexOf('.')) !== '.zip')) {
          this.$message.error('请上传zip或者rar压缩文件')
          return
        }
        if (fileSize / 1024 / 1024 > 500) {
          this.$message.error('上传文件大小不能超过500M')
          return
        }
        const formData = new FormData()
        formData.append('file', file)
        batchUploadCorrectedHomeworkFile(formData).then((res) => {
          if (res.success) {
            this.$message.success('上传成功')
            this.$refs.table.refresh()
          } else {
            this.$message.error('上传失败：' + res.message)
          }
        })
      },
      /**
       * 下载文件（所有文件）
       */
      sysFileInfoDownload(fileId) {
        this.cardLoading = true
        sysFileInfoDownload({ id: fileId })
          .then((res) => {
            this.cardLoading = false
            this.downloadfile(res)
          })
          .catch(() => {
            this.cardLoading = false
            this.$message.error('下载错误：获取文件流错误')
          })
      },
      downloadfile(res) {
        var blob = new Blob([res.data], { type: 'application/octet-stream;charset=UTF-8' })
        var contentDisposition = res.headers['content-disposition']
        var patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
        var result = patt.exec(contentDisposition)
        var filename = result[1]
        var downloadElement = document.createElement('a')
        var href = window.URL.createObjectURL(blob) // 创建下载的链接
        var reg = /^["](.*)["]$/g
        downloadElement.style.display = 'none'
        downloadElement.href = href
        downloadElement.download = decodeURI(filename.replace(reg, '$1')) // 下载后文件名
        document.body.appendChild(downloadElement)
        downloadElement.click() // 点击下载
        document.body.removeChild(downloadElement) // 下载完成移除元素
        window.URL.revokeObjectURL(href)
      },
      changeCourse(courseId) {
        this.loadCourseScheduleFrequencyList(courseId)
        this.queryParam.projectId = undefined // 清空项目的选择
        const collId = courseId ? this.courseList.find((item) => (item.id = courseId)).collId : null
        this.getProjectList(collId)
      },
      /**
       * 下载学生作业
       */
      batchDownloadStudentHomework() {
        const paramIds = this.selectedRows
          .filter((item) => item.homeworkId != null)
          .map((item) => {
            return { id: item.homeworkId }
          })
        if (paramIds.length === 0) {
          this.$message.error('未选择任何有效作业数据')
          return
        }
        batchDownloadStudentHomework(paramIds).then((res) => {
          this.$refs.batchExport.downloadfile(res)
        })
      },
      /**
       * 下载批改后作业
       */
      batchDownloadCorrectedHomework() {
        const paramIds = this.selectedRows
          .filter((item) => item.homeworkId != null)
          .map((item) => {
            return { id: item.homeworkId }
          })
        if (paramIds.length === 0) {
          this.$message.error('未选择任何有效的批改后的作业数据')
          return
        }
        batchDownloadCorrectedHomework(paramIds).then((res) => {
          this.$refs.batchExport.downloadfile(res)
        })
      },
      changeSchoolYear(schoolYearId) {
        this.queryParam.termId = undefined
        this.getSchoolTermList(schoolYearId)
      },
      deleteStuHomework(homeworkId) {
        homeworkDelete([{
          id: homeworkId
        }]).then(res => {
          if (res.success) {
            this.$refs.table.refresh(true)
          }
        })
      }
    }
  }
</script>
<style lang="less">
  .table-operator {
    margin-bottom: 18px;
  }

  button {
    margin-right: 8px;
  }
</style>
